<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\controller\AesUtil;
use think\Config;
use addons\workorder\library\General;
use app\common\controller\Frontend;
use addons\workorder\model\Orders;
use app\common\model\User;
use Exception;
use WechatPay\GuzzleMiddleware\Util\MediaUtil;
use GuzzleHttp\Exception\RequestException;
use WechatPay\GuzzleMiddleware\WechatPayMiddleware;
use WechatPay\GuzzleMiddleware\Util\PemUtil;
use app\api\controller\Complaincommon;

/**
 * 会员接口
 */
class Complainlkc extends Frontend
{
    protected $noNeedLogin = ['complainCallBack','testInfo','uploadImg','replyComplain','closeComplain','uploadImg4','getCertificateLKC','getComplainDetail','getComplainImage','getHistorys','createComplainUrl'];
    protected $noNeedRight = '*';
    protected $General = null;

    public $wechatpayCertificate = null;
    public $merchantId = null; // 商户号
    public $merchantSerialNumber = null; // 商户API证书序列号
    public $merchantPrivateKey = null; // 商户私钥
    public $client = null;

    public function _initialize()
    {

        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }


    // 投诉的回调地址
    public function complainCallBack(){
        $xml = file_get_contents('php://input');
        $sessionKey = "2a17661076b4a9b9f0f05f12f38304dd";
        file_put_contents('./1.txt', json_encode($xml).PHP_EOL,FILE_APPEND);
        $this->decrypt($xml,$sessionKey);
        return 200;
        
    }

    public function replyComplain($complaint_id,$complainted_mchid,$response_content = null,$response_images = null){
        if($complaint_id && $complainted_mchid){
            $complainObject = new Complaincommon(NUll , NULL , $complainted_mchid);

            try {  
                $url = "https://api.mch.weixin.qq.com/v3/merchant-service/complaints-v2/{$complaint_id}/response";
                $data = [
                    "complainted_mchid" =>$complainted_mchid
                ];
                $data['response_content'] = $response_content??'图片';
                if($response_images){
                    $data['response_images']  = explode(',', trim($response_images, ','));
                }
                
                $certificate_differ = db('certificate_differ')->where('MCHID',$complainted_mchid)->find();
                //print_r($certificate_differ);

                $sign                        = $complainObject -> getSign_fen($url, 'POST',json_encode($data),$complainted_mchid,$certificate_differ['serial_number']);//获取签名
                $sign                        = 'WECHATPAY2-SHA256-RSA2048 '.$sign; //认证类型  拼接 签名
                $res = http_post_json_complain($url,json_encode($data),  $sign);// http_post_json($url, $data, $sign); //请求接口
                if($res[0]==204){
                    return true;
                }
    
            } catch (RequestException $e) {
                // 进行错误处理
                echo $e->getMessage()."\n";
                if ($e->hasResponse()) {
                    echo "failed,resp code = " . $e->getResponse()->getStatusCode() . " return body = " . $e->getResponse()->getBody() . "\n";
                }
                return;
            }
        }
        
    }

    public function arrayToJson($array) {
        $jsonObject = '{';
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $jsonObject .= '"' . $key . '": ' . $this->arrayToJson($value) . ',';
            } else {
                $jsonObject .= '"' . $key . '": "' . $value . '",';
            }
        }
        $jsonObject = rtrim($jsonObject, ',');
        $jsonObject .= '}';
        return $jsonObject;
    }
     

    //关闭投诉
    public function closeComplain($complaint_id,$complainted_mchid){
        $complainObject = new Complaincommon(NUll , NULL , $complainted_mchid);
        try {

            $url = "https://api.mch.weixin.qq.com/v3/merchant-service/complaints-v2/{$complaint_id}/complete";
            $data = [
                "complainted_mchid" =>$complainted_mchid
            ];
            $certificate_differ = db('certificate_differ')->where('MCHID',$complainted_mchid)->find();

            $sign                        = $complainObject -> getSign_fen($url, 'POST',json_encode($data),$complainted_mchid,$certificate_differ['serial_number']);//获取签名
            $sign                        = 'WECHATPAY2-SHA256-RSA2048 '.$sign; //认证类型  拼接 签名
            
            http_post_json_complain($url,json_encode($data),  $sign);// http_post_json($url, $data, $sign); //请求接口
        }catch (RequestException $e) {
            // 进行错误处理
            echo $e->getMessage()."\n";
            if ($e->hasResponse()) {
                echo "failed,resp code = " . $e->getResponse()->getStatusCode() . " return body = " . $e->getResponse()->getBody() . "\n";
            }
            return;
        }
    }

    //获取投诉详情
    public function getComplainDetail($complaint_id){

        // 接下来，正常使用Guzzle发起API请求，WechatPayMiddleware会自动地处理签名和验签
        try {
            $resp = $this->client->request('GET', 'https://api.mch.weixin.qq.com/v3/merchant-service/complaints-v2/'.$complaint_id, [ // 注意替换为实际URL
                'headers' => [ 'Accept' => 'application/json' ]
            ]);
            return $resp->getBody();
        } catch (RequestException $e) {
            // 进行错误处理
            echo $e->getMessage()."\n";
            if ($e->hasResponse()) {
                echo $e->getResponse()->getStatusCode().' '.$e->getResponse()->getReasonPhrase()."\n";
                echo $e->getResponse()->getBody();
            }
            return;
        }

    }

    

    public function testInfo(){
        $xml = '{"id":"eaf3af48-c77c-5a66-b05d-9e2bc19ddf8c","create_time":"2025-04-15T15:12:25+08:00","resource_type":"encrypt-resource","event_type":"COMPLAINT.STATE_CHANGE","summary":"u6295u8bc9u72b6u6001u53d8u66f4","resource":{"original_type":"complaint","algorithm":"AEAD_AES_256_GCM","ciphertext":"esdV5C6m4xgFB8kEYq6ZlAEICJqOHC4b8WXBCihB3uCvdX0f9aA8rA76624LZhtx44+400cjjcSu/cit+03l3A00HIvqnPx6O5OAn1GmyWu9RucslOAihAIwnBReQ/RIo0khPypG4/PgSVGFe95A8KNLU9kkGJMI8+NXg73oyB98liowBSelb/iASvo+Lh14Poii/e612vMJI2x2GkMFQLsWjtUt9mHBFUJYF9O/RnDDMN6g8TevTWeZPhuvigwaPxNsTf6RCtr9smYoeY3xuAaB+DMluZ4VV4wcNACa3YuzlKOtJ6xBEyvuRpk4VT1mFjzjPSqKL2dvjXFpFBZZVUtVTkUOE2v/KLfqBl4kRolC+jelXR6SKZ4RCVbC4WzDRTCq32k3GHOevs+FFRztlMdwkPyMZdKndfyEouUiovlLhu26Mi1hK/BE7Q+h9EPqVSE2cJiiUihNzVXS7VI/QtW30huJqvZRRI8p0EDSosErac4Jo3cykkqM6PaylxcnFITSv0G5Mq7HNgTntyo=","associated_data":"complaint","nonce":"6SNFCAyFm5pk"}}';
        $this->decrypt($xml,'2a17661076b4a9b9f0f05f12f38304dd');
        exit;
        $data = json_decode($xml,true);
        $ciphertext = $data['resource']['ciphertext'];
        $nonce = $data['resource']['nonce'];
        $associated_data = $data['resource']['associated_data'];
        $aesutil = new AesUtil('2a17661076b4a9b9f0f05f12f38304dd');
        $res = json_decode($aesutil->decryptToString($associated_data, $nonce, $ciphertext),true);

        $postData['out_trade_no'] = $out_trade_no = $res['out_trade_no'];
        $post_url = 'https://share.lkcsz.com/treasure/index/getMchidByOrderNo?orderNo='.$out_trade_no;
        $mch_id = curlPost($post_url,$postData);

        print_r([$res,$mch_id,$mch_id->data->mchid]);
    }

    
    // 解密函数
    public function decrypt($data,$sessionKey){
        $this->General = General::instance();
        
        $data = json_decode($data,true);
        $ciphertext = $data['resource']['ciphertext'];
        $nonce = $data['resource']['nonce'];
        if(isset($data['resource']) && !empty($data['resource'])){
            $associated_data = $data['resource']['associated_data'];
            $aesutil = new AesUtil($sessionKey);
            $res = json_decode($aesutil->decryptToString($associated_data, $nonce, $ciphertext),true);
            file_put_contents('log2.txt', json_encode($res)."\n", FILE_APPEND);
            if($res && ($res['action_type']=="CREATE_COMPLAINT" || $res['action_type']=="CONTINUE_COMPLAINT") || $res['action_type']=="USER_RESPONSE" || $res['action_type']=="RESPONSE_BY_PLATFORM" ){
                $postData['out_trade_no'] = $out_trade_no = $res['out_trade_no'];
                $post_url = 'https://share.lkcsz.com/treasure/index/getMchidByOrderNo?orderNo='.$out_trade_no;
                $mch_id = curlPost($post_url,$postData);
                file_put_contents('log3.txt', json_encode([$mch_id,$post_url])."\n", FILE_APPEND);
                $mch = $mch_id->data->mchid;
                $complainObject = new Complaincommon(NUll , NULL , $mch);


                $payer_phone = $res['payer_phone'];
                $complaint_id = $res['complaint_id'];
                $payer_phone = $res['payer_phone'];
                $postData['out_trade_no'] = $out_trade_no = $res['out_trade_no'];
                $workorder_orders = db('workorder_orders')->where('out_trade_no',$out_trade_no)->find();
                
                $userInfo = db('user')->where('username',$payer_phone)->find();
                $complaint_time = $res['complaint_time'];
                $amount = $res['amount'];
                $payer_phone = $res['payer_phone'];
                $complaint_detail = $res['complaint_detail']?$res['complaint_detail']:' ';
                $complaint_state = $res['complaint_state'];
                $transaction_id = $res['transaction_id'];
                $complaint_handle_state = $res['complaint_handle_state'];
                $action_type = $res['action_type'];

                if(!$userInfo){
                    $userid = $this->auth->register($payer_phone, '123456', '', $payer_phone);
                    $userInfo = db('user')->where('username',$payer_phone)->find();
                }

                $history = $complainObject->getHistorys($complaint_id);
                $history_arr = json_decode($history,true);
                if($userInfo){
                    if($history_arr['total_count']>0){
                        foreach($history_arr['data'] as $key=>$history_item){
                            $log_id = $history_item['log_id'];
                            $isset_log_id = db('workorder_records')->where('log_id',$log_id)->find();
                            if($isset_log_id) continue;
                            if($history_item['operate_type']=='USER_CREATE_COMPLAINT' ){
                                $row = [
                                    'complainted_mchid'=>isset($mch_id->data->mchid)?$mch_id->data->mchid:'',
                                    'out_trade_no'=>$out_trade_no,
                                    'amount' => $amount,
                                    'complaint_state' => $complaint_state,
                                    'transaction_id' => $transaction_id,
                                    'complaint_handle_state' => $complaint_handle_state,
                                    'action_type' => $action_type,
                                    'complaint_id' => $complaint_id,
                
                                    'title'=>$out_trade_no,
                                    'describe'=>$history_item['operate_details']?$history_item['operate_details']:' ',
                                    'mobile'=>$payer_phone,
                                    'createtime'=>$complaint_time,
                                    'updatetime'=>$complaint_time,
                                ];
                                if($sessionKey == '2a17661076b4a9b9f0f05f12f38304dd'){
                                    $category = 4;
                                }
                                $row['category_id'] = $category;
                                if(!$workorder_orders){
                                    $res_createReply = $this->General->createOrder($row, $userInfo['id']);
                                    $workorder_orders = db('workorder_orders')->where('out_trade_no',$out_trade_no)->find();
                                }

                                // 检查是否有图片
                                if(isset( $history_item['complaint_media_list']['media_url'])){
                                    $history_media_url = $history_item['complaint_media_list']['media_url'];
                                    foreach($history_media_url as $history_media_url_item){
                                        
                                        $media_res = $complainObject->getComplainImage($history_media_url_item);
                                        $media_res_arr = json_decode($media_res,true);
                                        if(isset($media_res_arr['media_id'])){
                                            if($userInfo){                                    
                                                if(isset($workorder_orders['out_trade_no']) && !empty($workorder_orders['out_trade_no'])){ // 同个订单，是回复
                                                    $row_replay = [
                                                        'reply_describe'=>$media_res_arr['full_path'],
                                                        'reply_confidential'=>'',
                                                        'reply_type'=>1,
                                                        'media_id'=>$media_res_arr['media_id'],
                                                        'log_id'=>$log_id,
                                                        
                                                    ];
                                                    $order = Orders::get($workorder_orders['id']);
                                                    $user = User::get($userInfo['id']);
                                                    $res_createReply = $this->General->createReply($order, $user, NULL, $row_replay);
                                                    $this->assignconfig('editor_name', $this->getEditorName());
                                                }
                                            }
                                        }
                                    }
                                }

                                continue;
                            }
                            
                            $updateDate['status'] = 2;
                            db('workorder_orders')->where('out_trade_no',$out_trade_no)->update($updateDate);

                            if($history_item['operate_type']=='USER_RESPONSE' || $history_item['operate_type'] == 'USER_CONTINUE_COMPLAINT'){
                                if(isset( $history_item['complaint_media_list']['media_url'])){
                                    $history_media_url = $history_item['complaint_media_list']['media_url'];
                                    foreach($history_media_url as $history_media_url_item){
                                        
                                        $media_res = $complainObject->getComplainImage($history_media_url_item);
                                        $media_res_arr = json_decode($media_res,true);
                                        if(isset($media_res_arr['media_id'])){
                                            if($userInfo){                                    
                                                if(isset($workorder_orders['out_trade_no']) && !empty($workorder_orders['out_trade_no'])){ // 同个订单，是回复
                                                    $row_replay = [
                                                        'reply_describe'=>$media_res_arr['full_path'],
                                                        'reply_confidential'=>'',
                                                        'reply_type'=>1,
                                                        'media_id'=>$media_res_arr['media_id'],
                                                        'log_id'=>$log_id,
                                                        
                                                    ];
                                                    $order = Orders::get($workorder_orders['id']);
                                                    $user = User::get($userInfo['id']);
                                                    $res_createReply = $this->General->createReply($order, $user, NULL, $row_replay);
                                                    $this->assignconfig('editor_name', $this->getEditorName());
                                                }
                                            }
                                        }
                                    }
                                }else{
                                    if(isset($workorder_orders['out_trade_no']) && !empty($workorder_orders['out_trade_no'])){ // 同个订单，是回复
                                        $row_replay = [
                                            'reply_describe'=>$history_item['operate_details'],
                                            'reply_confidential'=>'',
                                            'reply_type'=>0,
                                            'log_id'=>$history_item['log_id'],
                                            
                                        ];
                                        $order = Orders::get($workorder_orders['id']);
                                        $user = User::get($userInfo['id']);
                                        $res_createReply = $this->General->createReply($order, $user, NULL, $row_replay);
                                        $this->assignconfig('editor_name', $this->getEditorName());
                                    }
                                }
                            }
                           
                        }
                       
                    }
                }
    
            }elseif($res && $res['action_type']=="REFUND_SUCCESS" ){
                $out_trade_no = $res['out_trade_no'];
                $updateDate['status'] = 5;
                db('workorder_orders')->where('out_trade_no',$out_trade_no)->update($updateDate);
            }
        }
        
    }


    public function uploadImg($imgUrl,$mchid){
        $complainObject = new Complaincommon(NUll , NULL , $mchid);
        // 接下来，正常使用Guzzle发起API请求， WechatPayMiddleware 会自动地处理签名和验签
        $media = new MediaUtil($imgUrl);
        // 正常使用Guzzle发起API请求
        try {
            $resp = $complainObject->client->request('POST', 'https://api.mch.weixin.qq.com/v3/merchant-service/images/upload', [
                'body'    => $media->getStream(),
                'headers' => [
                    'Accept'       => 'application/json',
                    'content-type' => $media->getContentType(),
                ]
            ]);
            $img = json_decode($resp->getBody(), true);
            return $img['media_id'];
         } catch (Exception $e) {
            echo $e->getMessage()."\n";
            echo $e->getMessage(),$e->getLine(),$e->getFile();
            return;
        } 
    }
   
    // 创建投诉通知回调地址
    public function createComplainUrl($complainted_mchid){
        try {
            
            $url = "https://api.mch.weixin.qq.com/v3/merchant-service/complaint-notifications";
            $dsg['url'] = 'https://complain.lkcsz.com/api/Complainlkc/complainCallBack' ;
            
            $complainObject = new Complaincommon(NUll , NULL , $complainted_mchid);
            $certificate_differ = db('certificate_differ')->where('MCHID',$complainted_mchid)->find();

            $sign                        = $complainObject -> getSign_fen($url, 'POST',json_encode($dsg),$complainted_mchid,$certificate_differ['serial_number']);//获取签名
            $sign                        = 'WECHATPAY2-SHA256-RSA2048 '.$sign; //认证类型  拼接 签名
            
            $return                      = http_post_json_complain($url,json_encode($dsg),  $sign);// http_post_json($url, $dsg, $sign); //请求接口
            
            print_r($return);exit;
            
        } catch (RequestException $e) {
            // 进行错误处理
            echo $e->getMessage()."\n";
            if ($e->hasResponse()) {
                echo "failed,resp code = " . $e->getResponse()->getStatusCode() . " return body = " . $e->getResponse()->getBody() . "\n";
            }
            return;
        }
    }

    public function updateComplainUrl($complainted_mchid){
        try {
            
            $url = "https://api.mch.weixin.qq.com/v3/merchant-service/complaint-notifications";
            $dsg['url'] = "https://complain.lkcsz.com/api/Complainlkc/complainCallBack";

            $complainObject = new Complaincommon(NUll , NULL , $complainted_mchid);
            $certificate_differ = db('certificate_differ')->where('MCHID',$complainted_mchid)->find();

            $sign                        = $complainObject -> getSign_fen($url, 'PUT',json_encode($dsg),$complainted_mchid,$certificate_differ['serial_number']);//获取签名
            $sign                        = 'WECHATPAY2-SHA256-RSA2048 '.$sign; //认证类型  拼接 签名
            $return                      = http_put_json_complain($url,json_encode($dsg),  $sign);// http_post_json($url, $dsg, $sign); //请求接口
            
            print_r($return);exit;
            
        } catch (RequestException $e) {
            // 进行错误处理
            echo $e->getMessage()."\n";
            if ($e->hasResponse()) {
                echo "failed,resp code = " . $e->getResponse()->getStatusCode() . " return body = " . $e->getResponse()->getBody() . "\n";
            }
            return;
        }
    }

}

